package guda.demox.web.helper;

import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by well on 17/6/8.
 */
public class LogFilter implements Filter {

    private static final String remoteAddrKey="remoteAddr";
    private static final String referrerKey ="referrer";
    private static final String userAgentKey="userAgent";
    private static final String userIdkey="userId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(servletRequest instanceof HttpServletRequest){
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            MDC.put(remoteAddrKey, request.getRemoteHost());
            String referer = request.getHeader("Referer");
            if(referer!=null) {
                MDC.put(referrerKey, referer);
            }
            String userAgent = request.getHeader("User-Agent");
            if(userAgent!=null) {
                MDC.put(userAgentKey, userAgent);
            }
            Object user_id = request.getSession().getAttribute("USER_ID");
            if(user_id!=null) {
                MDC.put(userIdkey,String.valueOf( user_id));
            }
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {

    }
}
